Coiteration¶

🎨 zip¶

In [1]:
names = ['John', 'Juan', 'João', 'Giovanni']
ages = [23, 18, 24, 22]
zip(names, ages)
Out[1]:
<zip at 0x105e1ef00>
🤨
In [2]:
names = ['John', 'Juan', 'João', 'Giovanni']
ages = [23, 18, 24, 22]
list(zip(names, ages))
Out[2]:
[('John', 23), ('Juan', 18), ('João', 24), ('Giovanni', 22)]
In [3]:
names = ['John', 'Juan', 'João', 'Giovanni']
ages = [23, 18, 24, 22]

for name, age in zip(names, ages):
    print(f'{name} is {age} years old')
John is 23 years old
Juan is 18 years old
João is 24 years old
Giovanni is 22 years old

NOTES

  • draw out the lists
  • Show the pairings
  • zip creates tuples by pairing items in lists
In [4]:
names = ['John', 'Juan', 'João', 'Giovanni']
ages = [23, 18, 24, 22]
majors = ['Chemistry', 'Animation', 'Sociology', 'Secondary Education']

for name, age, major in zip(names, ages, majors):
    print(f'{name} is {age} years old and studies {major}')
John is 23 years old and studies Chemistry
Juan is 18 years old and studies Animation
João is 24 years old and studies Sociology
Giovanni is 22 years old and studies Secondary Education

NOTES

  • you can zip as many lists as you want
  • The size of the tuple you get out depends on the number of lists you zip
In [5]:
fruits = ['apple', 'pear', 'blueberry', 'grape', 'strawberry']
plant_types = ['tree', 'tree', 'bush', 'vine']

for fruit, plant_type in zip(fruits, plant_types):
    print(f'The {fruit} grows on a {plant_type}.')
The apple grows on a tree.
The pear grows on a tree.
The blueberry grows on a bush.
The grape grows on a vine.

NOTES

  • Zip stops as soon as one of the input lists runs out.
  • Be careful!
In [6]:
word1 = 'planter'
word2 = 'started'

for letter1, letter2 in zip(word1, word2):
    if letter1 == letter2:
        print(f'{letter1} == {letter2} ✅')
    else:
        print(f'{letter1} != {letter2}')
p != s
l != t
a == a ✅
n != r
t == t ✅
e == e ✅
r != d

NOTES

  • You can zip anything you can iterate: lists, strings, etc.

🎨 enumerate¶

In [7]:
enumerate(['Paula', 'Patty', 'Peter', 'Peregrin'])
Out[7]:
<enumerate at 0x10603f800>
In [8]:
list(enumerate(['Paula', 'Patty', 'Peter', 'Peregrin']))
Out[8]:
[(0, 'Paula'), (1, 'Patty'), (2, 'Peter'), (3, 'Peregrin')]
In [9]:
for index, name in enumerate(['Paula', 'Patty', 'Peter', 'Peregrin']):
    print(f'{index}: {name}')
0: Paula
1: Patty
2: Peter
3: Peregrin

Key Ideas¶

  • To iterate through multiple things at the same time, use zip
  • To get the index along with the item while iterating, use enumerate